/**
 * Created by jt on 2017/5/8.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/select2.min.js";
import "../../../unit/common/js/bootstrap_js/jquery.dataTables.js";
import "../../../unit/common/js/bootstrap_js/form-samples.js";
import "../../../unit/common/js/bootstrap_js/table-editable.js";

import {projSts} from "../config.js";
import projListTpl from "./getProj.handlebars";
import paginationTpl from "./paging.handlebars";

var token = sessionStorage.getItem('token');
if (token == null || token =='') {
    location.href = HOST_FRT+'/expert_grid/login.html';
}

var projList = {
    pageNo: 1,
    pageSize: 20,
    maxPage: 1,
    isFirstPage: false,
    isLastPage: false,
    total: 0,
    data:{},
    init: function(){
        this.getProjData()
            .then(this.renderprojList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    },
    getProjData: function() {
        return new Promise((resolve, reject)=>{
                let self = this;
        $.ajax({
            url: HOST_ADDR + `/cpmp/bidProjOnMngForExpt/queryGrdInfs/${self.pageNo}/${self.pageSize}`,
            type: 'post',
            dataType: 'json',
            headers: {
                'access_token': token,'login_type':'ums','IsMCompany':ISMCOMPANY
            },
            data:JSON.stringify(self.data),
            contentType: "application/json",
            success: function (resp) {
                if (resp.success) {
                    console.log(resp);
                    resolve(resp);
                }
                else {
                    alert(resp.msgInf);
                }
            },
            error: function (err) {
                console.log(err);
            }
        });

    });

    },
    // 渲染列表
    renderprojList: function(resp){
        let self = projList;
        // 处理数据begin
        self.total = resp.data.count;
        self.isFirstPage = self.pageNo === 1;
        self.maxPage = Math.ceil(self.total / self.pageSize);
        var datalist = [];
        $.each(resp.data.list,function(index,item){
            if(typeof(item.bidProjOnExptGrdInf) !='undefined' && item.bidProjOnExptGrdInf !=null){
                var obj = Object.assign(item, item.bidProjOnExptGrdInf);
                item = obj;
            }
            (index==1 || index==2 ) && console.log(index,item);
            item.projStsFmt = projSts[item.projGrdSts] || '暂无状态';
            if(item.isAgreed =='1' || item.isAgreed =='2'){  // 0: 初始值  1:同意   2:不同意
                item.projStsFmt = item.projStsFmt + (item.isAgreed=='1' ? "(同意)" : "(不同意)");
            }

            item.checkRstAvailabel = (item.projGrdSts == '02' && (item.projSts=='25' || item.projSts=='40' || item.projSts=='50'));
            item.viewAvailabel = (item.projGrdSts == '01'||item.projGrdSts == '02');
            item.openAvailabel = (item.projGrdSts == '00');
            item.subAvailabel = (item.projGrdSts == '01');
        });
        
        // 处理数据end
        if(self.pageNo * self.pageSize >= self.total){
            self.isLastPage = true;
        }else{
            self.isLastPage = false;
        }

        let resultHtml = projListTpl({projList: resp.data.list});
        $('tbody').html(resultHtml);
    },

    // 渲染分页
    renderPagination: function(){
        let self = projList;
        let pageList = [];
        for(let i=0; i<self.maxPage; i++){
            pageList.push({idx: i+1});
        }
        console.log(self.total);
        let paginationHtml = paginationTpl({
            begin: (self.pageNo-1) * self.pageSize + 1,
            end: self.isLastPage ? self.total : self.pageNo * self.pageSize,
            total: self.total,
            isLastPage: self.isLastPage,
            isFirstPage: self.isFirstPage,
            pageList: pageList

        });
        $('.J_pagination').html(paginationHtml);
        $('.page-item').each((index,item)=>{
            if($(item).data('index')===self.pageNo){
            console.log(this);
            $(item).addClass('active');
        }
            //最多显示7个页码
            if (Math.abs($(item).data('index')-self.pageNo) > 3) {
                $(item).css('display','none');
            }
    });
    },

    // 绑定事件
    bindEvent: function(){
        let self = projList;
        $('.J_prev').unbind().click(function(){
            if(self.pageNo > 1){
                self.pageNo = self.pageNo -1;
                self.renderList();
            }
        });
        $('.J_next').unbind().click(function(){
            if(self.pageNo < self.maxPage){
                self.pageNo = self.pageNo + 1;
                self.renderList();
            }

        });

        //首尾页
        $('.isFirst').unbind().click(function(){
            if(self.pageNo != 1){
                self.pageNo = 1;
                self.renderList();
            }
        });
        $('.isLast').unbind().click(function(){
            if(self.pageNo != self.maxPage){
                self.pageNo = self.maxPage;
                self.renderList();
            }
        });

        $('.page-item').unbind().click(function(){
            let $item = $(this);

            if(!$item.hasClass('active')){
                self.pageNo = $item.data('index');
                self.renderList();
            }
        });

        //搜索
        jQuery('.searchExp').unbind().click(function(){
            var searNam = jQuery('.searNam').val();
            self.data={};
            if (searNam != '' && searNam != null) {
                self.data.projNam = searNam;
            }
            self.renderList();
        });

        //评标按钮且秘钥不能为空
        jQuery('.getCode').click(function () {
            var sid = jQuery(this).parent('td').siblings('td.sid').text();
            getCode(sid);
        });
        //提交评分
        jQuery('.subResult').click(function () {
            var sid = jQuery(this).parent('td').siblings('td.sid').text();
            subRes(sid);
        });

    },

    // 渲染列表
    renderList(){
        this.getProjData()
            .then(this.renderprojList)
            .then(this.renderPagination)
            .then(this.bindEvent);
    }
};

App.init();
projList.init();
var subFlg =true;

function getCode(sta) {
    if(!subFlg){
        alert("请稍后再试！");
        setTimeout(function(){subFlg = true;},5000)
        return false;
    }
    subFlg = false;
    jQuery('.fade').css('display','none');
    jQuery('#modal-container-code').css('display','block');
    // alert(projId)
    jQuery.ajax({
        url: HOST_ADDR+'/cpmp/bidProjOnMngForExpt/sndGrdKey/'+sta,
        type: 'get',
        // data: JSON.stringify(data),
        dataType: 'json',
        contentType:"application/json",
        headers: {
            'access_token': token,'login_type':'ums'
        },
        success: function(resp){
            if (!resp.success) {
                console.log(resp.msgCod+' '+resp.msgInf);
                return;
            }
            subFlg = true;
            console.log(resp);
        },
        error:function(err){
            console.log(err);
        }
    });

    jQuery('.endCode').click(function () {
        if (jQuery('.codeInfo').val()!='') {
            let data = {
                "grdId": sta,
                "grdKey": jQuery('.codeInfo').val()
            };
            // console.log(data)
            jQuery.ajax({
                url: HOST_ADDR+'/cpmp/bidProjOnMngForExpt/bgnGrd',
                type: 'post',
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: "application/json",
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                success: function (resp) {
                    if (!resp.success) {
                        alert(resp.msgCod + ' ' + resp.msgInf);
                        return;
                    }
                    location.href = 'proj_list.html';
                },
                error: function (err) {
                    console.log(err);
                }
            });

        } else {
            jQuery('#needCode').css('display','block');
            jQuery(this).attr({'data-toggle':'modal','href':'#needCode'});
        }
    });
}

function subRes(sta) {
    jQuery.ajax({
        url: HOST_ADDR+'/cpmp/bidProjOnMngForExpt/subScrRst/'+sta,
        type: 'get',
        // data: JSON.stringify(data),
        dataType: 'json',
        contentType: "application/json",
        headers: {
            'access_token': token,'login_type':'ums'
        },
        success: function (resp) {
            if (!resp.success) {
                console.log(resp.msgCod + ' ' + resp.msgInf);
                alert(resp.msgCod + resp.msgInf);
            } else {
                console.log(resp);
                alert('提交成功！');
                window.location.reload();
            }
        },
        error: function (err) {
            console.log(err);
        }
    });
}